/**
 * PushPaperService.java
 * Version 1.0.0
 * Created on 2018年7月23日
 *
 */
package com.yincheng.oes.business.exam.pushpaper.service;

import com.yincheng.oes.business.config.PaperResultStatus;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yincheng.oes.business.exam.base.entity.Paper;
import com.yincheng.oes.business.exam.base.mapper.PaperMapper;
import com.yincheng.oes.business.exam.judgepaper.entity.PaperResult;
import com.yincheng.oes.business.exam.judgepaper.mapper.PaperResultMapper;
import com.yincheng.oes.sso.entity.User;
import com.yincheng.oes.sso.mapper.UserMapper;

/**
 * @author yangsy
 * @version 1.0.0
 * @since
 * 创建时间：2018年7月23日
 * <p>
 * 功能描述：推送试卷服务层
 * <p>
 * 邮箱地址：446948434@qq.com
 */
@Service
public class PushPaperService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PaperResultMapper paperResultMapper;

    @Autowired
    private PaperMapper paperMapper;

    /**
     * 将试卷推送给未被推送的学生
     *
     * @param paperId
     */
    @Transactional
    public void pushPaperToStudent(String paperId) {
        Paper paperOld = paperMapper.selectById(paperId);
        List<User> students = userMapper.selectUnpushedStudents(paperId);
        students.forEach(e -> {
            PaperResult paperResult = new PaperResult();
            paperResult.setId(UUID.randomUUID().toString());
            paperResult.setPaperId(paperId);
            paperResult.setStatus(PaperResultStatus.DURING_ANSWER.getStatus());// 未答题
            paperResult.setUserId(e.getUserId());
            paperResult.setUserName(e.getUserName());
            paperResultMapper.insert(paperResult);
        });
        int i = paperMapper.updateByVersion(paperOld);
        if (i == 0) {
            throw new IllegalArgumentException("正在推送中，请稍后再试");
        }
    }

    /**
     * 根据指定学生id推送某个试卷
     *
     * @param paperId
     * @param userIds
     */
    @Transactional
    public void pushPaperToStudents(String paperId, String userIds) {
        String[] userIdArray = userIds.split(",");
        for (String userId : userIdArray) {
            PaperResult paperResult = paperResultMapper.selectByPaperIdAndUserId(paperId, userId);
            if (paperResult == null) {
                paperResult = new PaperResult();
                paperResult.setId(UUID.randomUUID().toString());
                paperResult.setPaperId(paperId);
                paperResult.setStatus(PaperResultStatus.DURING_ANSWER.getStatus());// 未答题
                paperResult.setUserId(userId);
                paperResultMapper.insert(paperResult);
            }
        }
    }
}
